package com.kfit.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.kfit.permission.bean.Role;
import com.kfit.permission.bean.UserInfo;
import com.kfit.permission.service.UserInfoService;

@Component
public class CustomUserDetailsService implements UserDetailsService{
	
	@Autowired
	private UserInfoService userInfoService;

	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		System.out.println("CustomUserDetailsService.loadUserByUsername()");
		/*
		 * 1/ 通过username 获取到userInfo 信息.
		 * 2/ 通过User(UserDetails) 返回UserDetails.
		 */
		UserInfo userInfo = userInfoService.findByUsername(username);
		if(userInfo == null) {
			throw new UsernameNotFoundException("not found");
		}
		
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		
		for(Role role:userInfo.getRoles()) {
			authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
		}
		//authorities.add(new SimpleGrantedAuthority("ROLE_"+userInfo.getRole().name()));
		
		User userDetails  = new User(userInfo.getUsername(), userInfo.getPassword(), authorities);
		
		return userDetails;
	}

}
